<template>
    <div>
        this is todo list
        <button type="button" @click="getTodoList">从服务端获取TodoList</button>
        <button type="button" @click="getTodoListByAxios">通过Axios从服务端获取TodoList</button>
        <button type="button" @click="addTodo">增加TodoItem</button>
        <button type="button" @click="addTodo2">增加TodoItem(dispatch)</button>
        <button type="button" @click="changeStyle">改变style</button>
        <todo-item
            v-for="item in evalTodoList"
            :key="item.id"
            :item="item"
            :styleInfo="style"
            @finish="finishHandler(item.id)"
            >
        </todo-item>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { uniqueId } from 'lodash';
import { Action, Getter, Mutation } from 'vuex-class';
import { ITodoItem } from '@/typings/todo';

import TodoItem from './components/TodoItem.vue';
import mutationType from '@/store/mutation-type';
import { getTodoList, getTodoListByAxios } from '@/api/todo';

// Compnent注解，typescript的装饰器
@Component({
  components: {
    TodoItem,
  },
})
export default class TodoList extends Vue {
    @Getter('todolist')
    private todolist!: ITodoItem[]

    @Mutation(mutationType.ADD_TODO, { namespace: 'todo' })
    commitAddTodo!: any

    @Mutation(mutationType.CHANGE_TODO_STATUS, { namespace: 'todo' })
    commitTodoStatus!: any

    @Action(mutationType.ADD_TODO, { namespace: 'todo' })
    dispatchAddTodo!: any

    get evalTodoList() {
      return this.todolist;
    }

    style:any = {
      color: 'black',
    }

    addTodo() {
      const id = uniqueId();
      const item: ITodoItem = {
        id,
        text: '打豆豆',
        status: 'Wait',
      };
      this.commitAddTodo(item);
    }

    addTodo2() {
      const id = uniqueId('todo_');
      const item: ITodoItem = {
        id,
        text: '打豆豆',
        status: 'Wait',
      };
      this.dispatchAddTodo(item);
    }

    getTodoList() {
      const response = getTodoList();
      const { data } = response;
      const { length } = data;
      if (!length) {
        return;
      }
      this.dispatchAddTodo(data[0]);
    }

    async getTodoListByAxios() {
      const data = await getTodoListByAxios();
      const { length } = data;
      if (!length) {
        return;
      }
      this.dispatchAddTodo(data[0]);
    }

    finishHandler(id: string): void {
      this.commitTodoStatus(id);
    }

    changeStyle() {
      this.style.color = 'red';
    }
}
</script>

<style lang="less" scoped>

</style>
